<?php

/**
 * 前台会员通行证
 * File Name：PassportAdminService.php
 * File Encoding：UTF-8
 * File New Time：2014-4-29 9:22:06
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class UserPassport extends CApplicationComponent implements ArrayAccess {

    //存储用户uid的Key
    const key = 'user_id';

    //错误密码
    protected $error = NULL;
    //用户信息
    protected static $userInfo = array();
    //返回地址
    public $returnUrl = '/user/member/index.html';

    public function __get($name) {
        if (isset(self::$userInfo[$name])) {
            return self::$userInfo[$name];
        } else {
            $userInfo = $this->getInfo();
            if (!empty($userInfo)) {
                return $userInfo[$name];
            }
            return NULL;
        }
    }

    /**
     * 获取错误信息
     * @return type
     */
    public function getError() {
        return $this->error;
    }

    /**
     * 获取当前登录用户资料
     * @return array 
     */
    public function getInfo() {
        if (empty(self::$userInfo)) {
            $uid = $this->getCookieUid();
            self::$userInfo = $this->getLocalUser((int) $uid);
            if (!empty(self::$userInfo)) {
                self::$userInfo['id'] = self::$userInfo['UserID'];
                self::$userInfo['name'] = self::$userInfo['UserName'];
            } else {
                $cookie = Yii::app()->request->getCookies();
                unset($cookie[self::key]);
            }
        }
        return !empty(self::$userInfo) ? self::$userInfo : false;
    }

    /**
     * 获取cookie中的id
     * @return boolean
     */
    public function getCookieUid() {
        $cookie = Yii::app()->request->getCookies();
        if (!isset($cookie[self::key])) {
            return false;
        }
        $ciphertext = $cookie[self::key]->value;
        if (empty($ciphertext)) {
            return false;
        }
        $uid = Encrypt::authcode($ciphertext);
        if (empty($uid)) {
            return false;
        }
        return $uid;
    }

    /**
     * 检查是否已经登录，有登录返回登录uid
     * @return boolean
     */
    public function isLogin() {
        //获取cookie中的用户id
        $uid = $this->getCookieUid();
        if (empty($uid) || (int) $uid < 1) {
            return false;
        }
        return $uid;
    }

    /**
     * 登录后台并进行身份验证
     * @param type $identifier 验证条件，直接uid，用户名
     * @param type $password 明文密码
     * @param type $is_remeber_me 记录时间
     * @return boolean
     */
    public function login($identifier, $password, $is_remeber_me = 2592000) {
        if (empty($identifier) || empty($password)) {
            $this->error = '帐号或者密码为空！';
            return false;
        }
        //进行登录验证
        $userInfo = $this->getLocalUser($identifier, $password);
        if (empty($userInfo)) {
            return false;
        }
       if (empty($userInfo['Status'])) {
           $this->error = '您的帐号还没有激活，<a id="send"  href="'.yii::app()->getController()->createUrl("regEmailSuccesed", array("mail" => $userInfo['Email'])).'">点击激活</a>！';
           return false;
       }
        if ($userInfo['IsLock']) {
            $this->error = $userInfo['IsLock'] ? $userInfo['IsLock'] : '您的帐号已被锁定，无法登录！';
            return false;
        }
        //增加登录送积分
        //明文密码
        $userInfo['expresslyPassword'] = $password;
        return $this->registerLogin($userInfo, $is_remeber_me);
    }

    /**
     * 注册用户登录状态
     * @param array $user 用户基本信息
     * @param type $is_remeber_me 有效期，秒
     * @return boolean
     */
    public function registerLogin($user, $is_remeber_me = 604800) {
        if (is_object($user) && $user instanceof MemberModel) {
            $user = $user->attributes;
        }

        if (empty($user)) {
            return false;
        }
        //更新最后登录时间
        $model = MemberModel::model()->findByPk($user['UserID']);
        $model->LastLoginIP = Tool::getForwardedForIp();
        $model->LatLoginTime = time();
        $model->save(false, array('LastLoginIP', 'LatLoginTime'));
        //保持登录状态
        $cookie = new CHttpCookie(self::key, Encrypt::authcode($user['UserID'], ''));
        //设置有效期
        $cookie->expire = time() + (int) $is_remeber_me;
        Yii::app()->request->cookies[self::key] = $cookie;
        if(GROUP_NAME != 'admin'){
            //生成登录记录
            $data = array(
                'UserID' => $user['UserID'],
                'Type' => 1,            
            );
            MemberOperationModel::saveData($data);            
        }



        return true;
    }

    /**
     * 注销登录状态
     * @return boolean
     */
    public function logout() {
        //生成登录记录
        $data = array(
            'UserID' => yii::app()->user->id,
            'Type' => 2,            
        );
        MemberOperationModel::saveData($data);        
        Yii::app()->request->getCookies()->remove(self::key);
        return true;
    }

    /**
     * 根据提示符(username)和未加密的密码(密码为空时不参与验证)获取本地用户信息
     * @param type $identifier 为数字时，表示uid，其他为用户名
     * @param type $password 明文密码
     * @return boolean 成功返回用户信息array()，否则返回布尔值false
     */
    public function getLocalUser($identifier, $password = null) {
        if (empty($identifier)) {
            return false;
        }
        $model = MemberModel::model();
        $userInfo = $model->getUserInfo($identifier);
        if (empty($userInfo)) {
            $this->error = '该用户不存在！';
            return false;
        }
        //密码验证
        if (!empty($password)) {
            if (MemberModel::encrypt($password) != $userInfo['Password']) {
                $this->error = '帐号密码错误！';
                return false;
            }
        }
        //去除敏感
        unset($userInfo['Password']);
        return $userInfo;
    }

    public function offsetExists($index) {
        return isset(self::$userInfo[$index]);
    }

    public function offsetGet($index) {
        return self::$userInfo[$index];
    }

    public function offsetSet($index, $newvalue) {
        
    }

    public function offsetUnset($index) {
        
    }
    //临时存储的东西
    public function getFlash($key = 'gweasdadsdfweas'){
        $mixData = Yii::app()->session[$key];
        Yii::app()->session->remove($key);
        return $mixData;
    }

    public function setFlash($value, $key = 'gweasdadsdfweas'){
        Yii::app()->session->add($key, $value);
    }

    public function hasFlash($key = 'gweasdadsdfweas'){
        return Yii::app()->session[$key];
    }
}
